﻿
var TrackingHistroyWindows = new Array();


function historyWindow(){
	var pagesize = 15;
	var day = new Date();
	var day = new Date();
	var today = day.getFullYear() + '-' + padLeft((day.getMonth() + 1).toString(), "0", 2) + '-' + padLeft(day.getDate().toString(), "0", 2);
	var yyday = addDays(day, -1);
	var yestoday = yyday.getFullYear() + '-' + padLeft((yyday.getMonth() + 1).toString(), "0", 2) + '-' + padLeft(yyday.getDate().toString(), "0", 2);
	
	var _Config; // save user columnModel config(not include tracker defined);
	var _TrackerColumns=[];
	var _TrackerFields=[];
	var _showhistorydatafilter = false;
	var _showHDOP = false;
	
	if(typeof(showHistoryDataFilter) !='undefined'){
		if(showHistoryDataFilter){
			_showhistorydatafilter = true;
		}
	};

	if (typeof(showHDOP) != 'undefined') {
		if (showHDOP) {
			_showHDOP = true;
		}
	};
	
	var trackerstore = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url: 'HandlerSearchTrackerName',
			timeout: 240000
		}),
		reader: new Ext.data.JsonReader({
			fields: ['trackname','snid'],
			root: "data"
		})
	});

	trackerstore.load();
	
	var trackerDefinedFieldStore = new Ext.data.Store({
		 proxy: new Ext.data.HttpProxy({
			url: 'servicesandhandler/HandlerGetTrackerDefineFields.ashx',
			timeout: 240000
		}),
		reader: new Ext.data.JsonReader({
			fields: ['FieldName']
		})
	});
	
	trackerstore.on('load', function(store,records,options){
		var sssids = new String();
		store.each(function(record){
			sssids += (sssids.length>0?',':'') + record.get('snid');
		});
		
		trackerDefinedFieldStore.load({
			 params:{
				sssids:sssids
			}
		});
		
	});
	
	
	trackerDefinedFieldStore.on('load',function(store,records,options){
		var i;
		for(i=0;i<_TrackerColumns.length;i++){
			fields.remove(_TrackerFields[i]);
			_Config.remove(_TrackerColumns[i]);
		}
		store.each(function(record){
			var fname = record.get('FieldName');
			_TrackerFields.push(fname);
			fields.push(fname);
			//add tracker defined dymanic
			var columnname =fname;
			if(fname=="01FF")
				columnname = _ConfigResource_Fuel;
			var newClolumn = new Ext.grid.Column({
				header: columnname,
				sortable: true,
				menuDisabled: true,
				dataIndex: fname
			});
			_TrackerColumns.push(newClolumn);
			_Config.push(newClolumn);
		});
		grid.getColumnModel().setConfig(_Config)
		//historystore.reader.fields = fields;
		//historystore.fields = fields;
		historystore.reader = new Ext.data.JsonReader({
			fields:fields,
			root:"data",
			totalProperty: "totalCount"
		});
	});
	
	var trackNameCombo = new Ext.ux.form.CheckboxCombo({
		store: trackerstore,
		mode:'local',
		displayField:'trackname',
		width:200,
		valueField: 'snid',
		enableKeyEvents: true,
		editable: true
	});

	trackNameCombo.on('keyup', function() {
		trackerstore.filter('trackname', trackNameCombo.getRawValue(), true, false);
		trackNameCombo.bindStore(trackerstore);
	});

	trackNameCombo.on('blur', function() {
		trackerstore.clearFilter();
		trackNameCombo.bindStore(trackerstore);
		trackerDefinedFieldStore.load({
			 params:{
				sssids:trackNameCombo.getValue()
			}
		});
	});

	var speedCompareData = [['0', '>='], ['1', '<=']];

	var speedCompareStore = new Ext.data.ArrayStore({
		fields: ['cmdid', 'text'],
		data: speedCompareData
	});
	
	var fromDateEditor = new Ext.form.DateField({
		renderer:Ext.util.Format.dateRenderer('Y-m-d'),
		format:'Y-m-d',
		value:today 
	 });
	
	
	var fromTimeEditor = new Ext.form.TimeField({
		value:"00:00",
		format:'H:i',
		width:70
	});
	
	var toDateEditor = new Ext.form.DateField({
		renderer:Ext.util.Format.dateRenderer('Y-m-d'),
		format:'Y-m-d',
		value:today
	});
	
	var toTimeEditor = new Ext.form.TimeField({
		value:'23:59',
		format:'H:i',
		width:70
	});

	var speedCompareEditor = new Ext.form.ComboBox({
		editable:false,
		disableKeyFilter: true,
		typeAhead: false,
		mode: 'local',
		forceSelection: true,
		triggerAction: 'all',
		store: speedCompareStore,
		displayField: 'text',
		width: 50,
		valueField: 'text'
	});

	speedCompareEditor.setValue('>=');

	var speedNumberEditor = new Ext.form.NumberField({
		width:50,
		value: '0',
		allowBlank :false,
		blankText : _Message_BlankText,
		maxValue : 2000,
		minValue : 0,
		minText: _Message_MinText+' 0',
		maxText: _Message_MaxText+' 2000'
	});

	var fields = ["devicename", "gpstime", "receivedtime", "gpsavailable", "latitude", "longitude", "location", "speed", "altitude", "direction", "gpsexpression", { name: "hasgsmlocation", type: "boolean" }, { name: "gsmlatitude", type: "float" }, { name: "gsmlongitude", type: "float" }, { name: "gsmaccuracy", type: "float" }, { name: "alarminfo", type: "int" }, "satellites", "gsmsignal", { name: "journey", type: "int" }, { name: "runtime", type: "int" }, { name: 'HDOP', type: 'float' }];
	for (var m = 0; m < dymanicfieldnames.length; m++)
		fields.push(dymanicfieldnames[m]);
		
	var historystore = new Ext.data.Store({
		proxy:new Ext.data.HttpProxy({
			url:"HandlerSearchHistory",
			method:"POST",
			timeout:120000
		}),
		reader:new Ext.data.JsonReader({
			fields:fields,
			root:"data",
			totalProperty: "totalCount"
		})
	});
	
	var geoInterval;
	historystore.addListener('load', function(store, records) {
		var i;
		for (i = 0; i < records.length; i++) {
			var valid = records[i].get("gpsavailable");
			if (valid)
				records[i].set("gpsexpression", _TrackerMain_Valid);
			else
				records[i].set("gpsexpression", _TrackerMain_Invalid);
			var journey = (records[i].get("journey") / 1000).toFixed(2);
			if (showmiles)
				journey = kilos2miles(journey);
			records[i].set("journey", journey);
			var rtime = formatTime(records[i].get("runtime"));
			records[i].set("runtime", rtime);
			
			if(showmiles)
				records[i].set("speed", kilos2miles(records[i].get("speed")));
			
		}

		if (addressCb.getValue() == true) {

			if (!Ext.isEmpty(geoInterval))
				window.clearInterval(geoInterval);
			var i = 0;
			var count = historystore.getCount(), recycleTimes = 0;
			if (count > 0) {
				geoInterval = window.setInterval(function() {
					if (recycleTimes >= 10) {
						i++;
						recycleTimes = 0;
					}
					if (i == count) {
						window.clearInterval(geoInterval);
						return;
					}
					else {
						var record = store.getAt(i);
						imap.geoCoder(String(record.data.latitude), String(record.data.longitude),
								function(address, index) {
									if (address == "") {
										recycleTimes++;
										return;
									}
									record.set("location", address);
									i += index;
								});
					}
				}, 1000);
			}
		}
	});

	var trackpointsfields = ["gpstime", "latitude", "longitude", "speed", "direction", "otherinfo", { name: "stopped", type: "bool" }, "stoppedtime"];
		
	//var trackpointreader = new Ext.data.JsonReader({},trackpointsfields);

	//last location interval store
	var trackpointstore = new Ext.data.Store({
		reader: new Ext.data.JsonReader({
			fields: trackpointsfields,
			root:"data",
			stoptime:"stoptime", //本次搜索停止时间
			end:"end"
		}),
		proxy : new Ext.data.HttpProxy({
			url: 'servicesandhandler/HandlerGetTrackPoints.ashx',
			timeout: 240000
		})
		
	});


	var addressCb = new Ext.form.Checkbox({ checked: false });
	
	function showendcallback(tmpmap) {
		if (trackpointstore.reader.jsonData.end == 0) {
			trackpointstore.reload({
				params: {
					trackName: trackNameCombo.getRawValue(),
					fromtime: trackpointstore.reader.jsonData.stoptime,
					totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
					filter: _showhistorydatafilter ? chkHistoryDataFilter.getValue() : true,
					speedCompare: speedCompareEditor.getRawValue(),
					speedNumber: speedNumberEditor.getRawValue(),
					pagesize: 150

				}
			, callback: function() {
				if (trackpointstore.getCount() > 0)
					tmpmap.drawAnimateHistoryLine(trackpointstore, _TrackerMain_GPSTime, _TrackerMain_Speed, showendcallback);
			}
			});
		}
	}
	var tbar = new Ext.Toolbar({
		items: [_Alarm_TrackerName + ':',
		trackNameCombo,
		{
			xtype: 'tbseparator', width: 5
		},
		_Alarm_FromTime + ':',
		fromDateEditor,
		{
			xtype: 'tbseparator', width: 5
		},
		fromTimeEditor,
		{
			xtype: 'tbseparator', width: 5
		},
		_Alarm_ToTime + ':',
		toDateEditor,
		{
			xtype: 'tbseparator', width: 5
		},
		toTimeEditor,
		{
			xtype: 'tbseparator', width: 5
		},
		_TrackerMain_Speed + ':',
		speedCompareEditor,
		speedNumberEditor,
		'-',
		_TrackerMain_ARP,
		addressCb,  //_Distance_Unit+":", distanceUnitChangeComb, '-',
		{
		xtype: 'tbseparator', width: 5
	},
		{
			tooltip: { text: _TrackerMain_Search, autoHide: true },
			icon: 'Content/images/search16.gif',
			handler: function () {
				historystore.reload({
					params: {
						trackName: trackNameCombo.getRawValue(),
						fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
						totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
						start: 0,
						limit: pagesize,
						speedCompare: speedCompareEditor.getRawValue(),
						speedNumber: speedNumberEditor.getRawValue()
					}
				});

			}
		},
		{
			tooltip: { text: _TrackerMain_ShowTrackLineInMap, autoHide: true },
			icon: 'Content/images/history16.gif',
			handler: function () {

				var ss = trackNameCombo.getRawValue();

				if (ss.length > 0 && ss.indexOf(',') == -1) {
					Ext.MessageBox.show({
						msg: _TrackerMain_Loading,
						progressText: _TrackerMain_Loading,
						width: 300,
						wait: true,
						waitConfig: { interval: 200 }
					});

					trackpointstore.reload({
						params: {
							trackName: trackNameCombo.getRawValue(),
							fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
							totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
							filter: _showhistorydatafilter ? chkHistoryDataFilter.getValue() : true,
							speedCompare: speedCompareEditor.getRawValue(),
							speedNumber: speedNumberEditor.getRawValue(),
							pagesize: 150
						},
						callback: function () {
							Ext.MessageBox.hide();
							if (trackpointstore.getCount() > 0) {
								var rmap;
								var butStartStop = new Ext.Button({
									tooltip: { text: _AnimateControl_Stop, autoHide: true },
									icon: 'Content/images/player_stop.png',
									handler: function () {
										if (butStartStop.tooltip.text == _AnimateControl_Stop) {
											rmap.stopAnimate();
											butStartStop.setTooltip({ text: _AnimateControl_Continue, autoHide: true });
											butStartStop.setIcon('Content/images/player_play.png');
										}
										else {
											rmap.startAnimate();
											butStartStop.setTooltip({ text: _AnimateControl_Stop, autoHide: true });
											butStartStop.setIcon('Content/images/player_stop.png');
										}

									}
								});
								var tbar = new Ext.Toolbar({
									items: [{
										tooltip: { text: _AnimateControl_ToStart, autoHide: true },
										icon: 'Content/images/player_start.png',
										handler: function () {
											rmap.toStartPoint();
										}
									}, {
										tooltip: { text: _AnimateControl_SlowDown, autoHide: true },
										icon: 'Content/images/player_rew.png',
										handler: function () {
											rmap.slowDownAnimate();
										}
									}, butStartStop
								, {
									tooltip: { text: _AnimateControl_SpeedUp, autoHide: true },
									icon: 'Content/images/player_fwd.png',
									handler: function () {
										rmap.speedUpAnimate();
									}
								}, {
									tooltip: { text: _AnimateControl_ToEnd, autoHide: true },
									icon: 'Content/images/player_end.png',
									handler: function () {
										rmap.toEndPoint();
									}
								}

										]

								});

								var win = createHistoryMapWindow(_TrackerMain_HistoryLine + '(' + trackNameCombo.getRawValue() + ')', tbar);

								win.show(); // 显示出来
								TrackingHistroyWindows.push(win);
								rmap = createMap(win.getMap(), true, null, gmapurl, butStartStop, _AnimateControl_Stop, _AnimateControl_Continue, true);
								rmap._parkingTimeCap = _Alarm_ParkingTime;

								win.addListener('beforeclose', function (p) {
									rmap.stopAnimate();
									setTimeout(function () {
										if (TrackingHistroyWindows.indexOf(p) != -1) {
											TrackingHistroyWindows.remove(p);
										}
									}, 1000);
								});
								nextwindowx += 20;
								nextwindowy += 20;
								rmap.drawAnimateHistoryLine(trackpointstore, _TrackerMain_GPSTime, _TrackerMain_Speed, showendcallback, (speedNumberEditor.getValue() > 0));
								var autoshowpoi = getCookie("showallpoi") == 'false' ? false : true;
								if (autoshowpoi) {
									showPOI("", rmap);
								}

							}
							else {
								Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
								Ext.Msg.show({
									title: _TrackerMain_Title,
									msg: _Message_NoDataInSelection,
									buttons: Ext.Msg.OK,
									animEl: 'elId',
									icon: Ext.MessageBox.WARNING
								});
							}
						}
					})


				}
				else {
					Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
					Ext.Msg.show({
						title: _TrackerMain_Title,
						msg: _Message_MustChooseOne,
						buttons: Ext.Msg.OK,
						animEl: 'elId',
						icon: Ext.MessageBox.WARNING
					});
				}
			}
		},
		{
			tooltip: { text: _TrackerMain_ExportToExcel, autoHide: true },
			icon: 'Content/images/excel16.gif',
			handler: function () {

				if (!Ext.fly('historyexcel')) {
					var frm = document.createElement('form');
					frm.id = 'historyexcel';
					frm.name = id;
					frm.style.display = 'none';
					document.body.appendChild(frm);
				}
				var requestaddress = false;
				requestaddress = addressCb.getValue();
				if (typeof (pcsaddress) != 'undefined') {
					requestaddress = pcsaddress && addressCb.getValue();
				}
				Ext.Ajax.request({
					url: 'HandlerExcel',
					form: Ext.fly('historyexcel'),
					method: 'POST',
					params: {
						exceltype: 'history',
						start: 0,
						limit: 60000,
						trackName: trackNameCombo.getRawValue(),
						fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
						totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
						speedCompare: speedCompareEditor.getRawValue(),
						speedNumber: speedNumberEditor.getRawValue(),
						requestaddress: requestaddress ? "1" : "0"
					},
					isUpload: true
				});

			}
		}
		/*
		, {
			tooltip: { text: _TrackerMain_ExportToKML, autoHide: true },
			icon: 'Content/images/kml.gif',
			handler: function () {
				var ss = trackNameCombo.getRawValue();

				if (ss.length > 0 && ss.indexOf(',') == -1) {
					if (!Ext.fly('historykml')) {
						var frm = document.createElement('form');
						frm.id = 'historykml';
						frm.name = id;
						frm.style.display = 'none';
						document.body.appendChild(frm);
					}
					Ext.Ajax.request({
						url: 'servicesandhandler/HandlerKML.ashx',
						form: Ext.fly('historykml'),
						method: 'POST',
						params: {
							exceltype: 'history',
							start: 0,
							limit: 60000,
							trackName: trackNameCombo.getRawValue(),
							fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
							totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
							speedCompare: speedCompareEditor.getRawValue(),
							speedNumber: speedNumberEditor.getRawValue()
						},
						isUpload: true
					});
				}
				else {
					Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
					Ext.Msg.show({
						title: _TrackerMain_Title,
						msg: _Message_MustChooseOne,
						buttons: Ext.Msg.OK,
						animEl: 'elId',
						icon: Ext.MessageBox.WARNING
					});
				}
			}
		}
		*/
		]
	});
	
	var lblShowHistoryDataFilter = new Ext.form.Label({
		text:_Auto_Filter_Data
	});
	
	var chkHistoryDataFilter = new Ext.form.Checkbox({
		checked:true
	});
	
	if(_showhistorydatafilter){
		tbar.insert(21,lblShowHistoryDataFilter);
		tbar.insert(22,chkHistoryDataFilter);
	}
	
	var headerspeedstr = showmiles ? _Alarm_Header_Speed + '(' + _TrackerMain_MPH + ')' : _Alarm_Header_Speed;
	var headerJourney = showmiles ? _TrackerMain_JourneyMiles : _TrackerMain_JouneryKM;
		var cm = [
			{ header: _Alarm_Header_Name, width: 75, sortable: true, menuDisabled: true, dataIndex: 'devicename' },
			{ header: _Alarm_Header_GPSTime, width: 85, sortable: true, menuDisabled: true, dataIndex: 'gpstime'
				/*,renderer:function(val){
				return Date(val.toString().substring(6,val.toString().length-2));
				}*/
			},
			{ header: _Alarm_Header_RecTime, width: 85, sortable: true, menuDisabled: true, dataIndex: 'receivedtime'
				/*,renderer:function(val){
				return Date(val.toString().substring(6,val.toString().length-2));
				}*/
			},
			{ header: _Alarm_Header_GpsVaild, width: 65, sortable: true, menuDisabled: true, dataIndex: 'gpsexpression' },
			{ header: 'HDOP', width: 65, sortable: true, menuDisabled: true, hidden:(!_showHDOP), dataIndex: 'HDOP' },
			{ header: _Alarm_Header_Latitude, width: 85, sortable: true, menuDisabled: true, dataIndex: 'latitude' },
			{ header: _Alarm_Header_Longitude, width: 85, sortable: true, menuDisabled: true, dataIndex: 'longitude' },
			{ header: _Alarm_Header_Location, width: 100, sortable: true, menuDisabled: true, dataIndex: 'location' },
			{ header: _Alarm_Header_Altitude, width: 60, sortable: true, menuDisabled: true, dataIndex: 'altitude' },
			{ header: headerspeedstr, width: 85, sortable: true, menuDisabled: true, dataIndex: 'speed' },
			{ header: _Alarm_Header_Angle, width: 60, sortable: true, menuDisabled: true, dataIndex: 'direction' },
			{ header: _Alarm_AlarmType, width: 60, sortable: true, menuDisabled: true, dataIndex: 'alarminfo',
				renderer: function(val) {
					return getAlarmStringFromAlarmType(val);
				}
			},
			{ header: _TrackerMain_Satellites, width: 60, sortable: true, menuDisabled: true, dataIndex: 'satellites' },
			{ header: _TrackerMain_GSMSignal, width: 60, sortable: true, menuDisabled: true, dataIndex: 'gsmsignal' },
			{ header: headerJourney, width: 60, sortable: true, menuDisabled: true, dataIndex: 'journey' },
			{ header: _TrackerMain_RunTime, width: 60, sortable: true, menuDisabled: true, dataIndex: 'runtime' }
		];
	
	for (m = 0; m < dymanicfieldnames.length; m++) {
		cm.push(new Ext.grid.Column({
			header: dymanicfieldnames[m],
			sortable: true,
			menuDisabled: true,
			dataIndex: dymanicfieldnames[m]
		}));
	}

	var grid = new Ext.grid.GridPanel({
		store: historystore,  
		loadMask: true,
		title: _Alarm_HistoryGrid,
		columns: cm,
		width:805,
		height:450
	});
	
	 _Config =  grid.getColumnModel().config;

		//grid.reconfigure(grid.getStore(),
	grid.addListener("rowdblclick", function(grid, index) {
		var record = grid.getStore().getAt(index);
		/*
		var win = createHistoryMapWindow(_TrackerMain_HistoryPoint + '(' + record.get('devicename') + ',' + record.get('gpstime') + ')');
		win.show();
		nextwindowx += 20;
		nextwindowy += 20;
		var rmap = createMap(win.getMap(), true, null, gmapurl); //new MSGMap(win.getMap(), true, null, gmapurl);
		rmap.drawHistoryPoint(record);
		*/

		var longitude = parseFloat(record.get("longitude"));
		var latitude = parseFloat(record.get("latitude"));
		var newMap = Sample.ExtGMap.initpos(latitude,longitude);

		var gmapwindow = new Ext.Window({
			title: _TrackerMain_HistoryPoint + '(' + record.get('devicename') + ',' + record.get('gpstime') + ')',
			closable: true,
			width: 500,
			height: 450,
			minimizable: false,
			items: [newMap]
		});
		gmapwindow.show();
	});
	
	var taskButton;
	var historywindow = new Ext.Window({
		title: _Alarm_HistoryWindow,
		layout: 'fit',
		height: 500,
		width: 1150,
		items: grid,
		tbar: tbar,
		iconCls:'report-history',
		closeAction: 'close',
		minimizable: true,
		constrain:true,
		bbar: new Ext.PagingToolbar({
			pageSize: pagesize,
			store: historystore,
			beforePageText: _Alarm_Page,
			refreshTex: _Alarm_Refresh,
			displayMsg: _Alarm_Displaying,
			emptyMsg: _Alarm_Alarm_emptyMsg,
			displayInfo: true
		}),
		listeners: {
			'minimize': function() {
				addTaskButtonForWindow(historywindow);
			}
		}

	});
	historystore.on('beforeload',function(store){
		historystore.baseParams = { start		: 'start',
									limit		: 'limit',
									trackName	: trackNameCombo.getRawValue(),
									fromtime	: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
									totime		: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
									speedCompare: speedCompareEditor.getRawValue(),
									speedNumber	: speedNumberEditor.getRawValue() 
								  } 
	}) 
	historywindow.show();
};